package 剑指offer;

/**
 * @description:
 * @author: ywk
 * @date: 2021-03-13
 */
public class 正则表达式 {
    //处理点号「.」通配符
    static boolean isMatchDot(String text, String pattern, int i, int j) {
        if (j == pattern.length()) {
            return i == text.length();
        }
        return (text.charAt(i) == pattern.charAt(j) || pattern.charAt(j) == '.') && isMatchDot(text, pattern, i + 1, j + 1);
    }    //处理「*」通配符

    static boolean isMatchStar(String text, String pattern, int i, int j) {
        if (i >= text.length() && j >= pattern.length()) {
            return true;
        }
        boolean first = false;
        if (j < pattern.length()) {
            first = pattern.charAt(j) == '.';
            if (i < text.length()) {
                first = first || pattern.charAt(j) == text.charAt(i);
            }
        }
        if (j < pattern.length() - 1 && pattern.charAt(j + 1) == '*') {
            return isMatchStar(text, pattern, i, j + 2) || first && isMatchStar(text, pattern, i + 1, j);
        }
        return first && isMatchStar(text, pattern, i + 1, j + 1);
    }    //处理「*」通配符,处理点号「.」通配符

    static boolean isMatchAll(String text, String pattern, int i, int j, int realIndex) {
        if (i >= text.length() && realIndex >= pattern.length()) {
            return true;
        }
        boolean first = false;
        if (j < pattern.length()) {
            first = pattern.charAt(j) == '?'    ;
            if (i < text.length()) {
                first = first || pattern.charAt(j) == text.charAt(i);
            }
        }
        if (j < pattern.length() - 1 && pattern.charAt(j + 1) == '*') {
            return (isMatchAll(text, pattern, i, j + 2, realIndex + 2)) ||
                    (first && isMatchAll(text, pattern, i + 1, j, realIndex + 1));
        }
        return first && isMatchAll(text, pattern, i + 1, j + 1, realIndex + 1);
    }

    public static void main(String[] args) {
        System.out.println(isMatchAll("aa", "*", 0, 0, 0));
        System.out.println(isMatchStar("aaa", "*", 0, 0));
    }
}
